package app.auto.runner.base.utility.xml;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aliang.auto.R;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;

import androidx.annotation.RequiresApi;
import app.auto.AndroidInstance;
import app.auto.runner.base.BroadcastBuilder;
import app.auto.runner.base.DipUtil;
import app.auto.runner.base.DynamicHelper;
import app.auto.runner.base.action.ViewInflater;
import app.auto.runner.base.framework.CrashHandler;
import app.auto.runner.base.intf.MapBuilder;
import app.auto.runner.base.utility.ImageFileUtil;
import app.auto.runner.base.utility.ReadFileUtil;
import app.auto.runner.base.utility.ToastUtil;

public class Parser extends AndroidInstance {
    Activity aty;
    public ProduceView root;
    View getResult;
    private boolean settoview = true;
    private ImageOptions imageoptions;

    public Parser setSettoview(boolean settoview) {
        this.settoview = settoview;
        return this;
    }

    public static Parser withActivity(Activity paty) {
        Parser parser = new Parser();
        parser.aty = paty;
        return parser;
    }


    public Parser parse(String stringreader, ViewGroup vg, View v) {
        try {
            View view = null;
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            InputStream is = new ByteArrayInputStream(stringreader.getBytes());

            parser.setInput(is, "utf-8");
            parser.setInput(new StringReader(stringreader));
            return parse(parser, vg, v);
        } catch (Exception e) {
            CrashHandler.errorDialog(e);
        }
        return this;
    }

    boolean tosettag = true;

    public Parser setTosettag(boolean tosettag) {
        this.tosettag = tosettag;
        return this;
    }

    @SuppressLint("NewApi")
    public Parser parse(XmlPullParser parser, ViewGroup vg, View view) throws XmlPullParserException, IOException, IllegalAccessException, NoSuchFieldException {
//if(view!=null&&vg!=null){
//    if(view.getParent()==vg){
//        ProduceView produceView = new ProduceView(parser, vg, view, "").setSetTosettag(tosettag).invoke();
//        if (produceView.is()) return this;
//    }
//}
        int eventType = 0;// 循环取出数据
        String t = "";
        eventType = parser.getEventType();
        try {
            parser.nextTag();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Stack<ViewGroup> stack = new Stack<ViewGroup>();
        View root = null;
        String name = null;
        boolean passfirst = false;
        while ((eventType = parser.getEventType()) != XmlPullParser.END_DOCUMENT) {
            name = parser.getName();
            if (name == null) {
                if (eventType == XmlPullParser.END_TAG) {
                    if (view instanceof ViewGroup) {


                        if (stack.size() > 1) {
                            ViewGroup now = stack.pop();
                            stack.peek().addView(now);
                        } else {
                            stack.empty();
                        }

                    }
                }
                parser.next();
                continue;
            }

            if (eventType == XmlPullParser.START_DOCUMENT || eventType == XmlPullParser.START_TAG) {


                ProduceView produceView = new ProduceView(parser, passfirst ? null : vg, view, t).setSetTosettag(tosettag).produceview();
                this.root = produceView;
                passfirst = true;
//                if (produceView.is()) continue;
                view = produceView.getView();
                if (root == null) {
                    root = view;
                    this.getResult = root;
                    this.root = produceView;
                }
                t = produceView.getT();
                if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
                    stack.push((ViewGroup) view);

                } else {
                    if (stack.size() > 0) {
                        stack.peek().addView(view);
                    }
                }
                try {
                    produceView.invoke();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (name.contains(".")) {

                } else if (name.endsWith("SurfaceView")) {
                    name = "android.view." + name;
                } else {
                    name = "android.widget." + name;
                }
                View cr = null;
                try {

                    cr = (View) Class.forName(name)
                            .getConstructor(Context.class)
                            .newInstance(aty);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (cr instanceof ViewGroup) {

                    if (stack.size() > 1) {
                        ViewGroup now = stack.pop();
                        stack.peek().addView(now);
                    } else {
                        stack.empty();
                    }

                }
            }
            parser.next();
            view = null;

        }

        if (vg != null) {
//            if (root.getParent() != null) {
//                if (root.getParent() == vg) {
//
//                } else {
//                    ((ViewGroup) root.getParent()).removeView(root);
//                    vg.addView(root);
//                }
//
//            } else
            if (root != null) {
                if (root.getParent() == null) {
                    vg.addView(root);
                } else if (root.getParent() != vg) {
                    ((ViewGroup) root.getParent()).removeView(root);
                    vg.addView(root);
                }
            }
        }
        return this;
    }

    public View getView() {
        return getResult;
    }

    public ProduceView getProduceView() {
        return root;
    }

    public void setPadding(View view, int ppl, int ppr, int ppt, int ppb) {
        int pl = view.getPaddingLeft();
        int pr = view.getPaddingRight();
        int pt = view.getPaddingTop();
        int pb = view.getPaddingBottom();
        pl = ppl != -1 ? ppl : pl;
        pr = ppr != -1 ? ppr : pr;
        pt = ppt != -1 ? ppt : pt;
        pb = ppb != -1 ? ppb : pb;
        view.setPadding(pl, pt, pt, pb);
    }

    public static float dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return dipValue * scale;
    }

    public static float px2dip(Context context, float px) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return px / scale;
    }

    float dimenToPixel(String dimen) {
        if (dimen.trim().replace("dip", "").equals(""))
            return 0;
        else if (dimen.endsWith("dip"))
            return DynamicHelper.dipToPx(Float.parseFloat(dimen.substring(0, dimen.length() - 3)));
        else if (dimen.endsWith("dp"))
            return DynamicHelper.dpToPx(Float.parseFloat(dimen.substring(0, dimen.length() - 2)));
        else if (dimen.endsWith("sp"))
            return DynamicHelper.spToPx(Float.parseFloat(dimen.substring(0, dimen.length() - 2)));
        else if (dimen.endsWith("px"))
            return Integer.parseInt(dimen.substring(0, dimen.length() - 2));
        else if (dimen.endsWith("%"))
            return (int) (Float.parseFloat(dimen.substring(0, dimen.length() - 1)) / 100f * DynamicHelper.deviceWidth());
        else if (dimen.contains("match_parent") || dimen.contains("fill_parent"))
            return ViewGroup.LayoutParams.MATCH_PARENT;
        else if (dimen.contains("wrap_content"))
            return ViewGroup.LayoutParams.WRAP_CONTENT;
        else
            return Integer.parseInt(dimen);
    }

    @Override
    public AndroidInstance use(Object mp, Object... p) {
        return null;
    }

    public class ProduceView {
        private boolean myResult;
        private XmlPullParser parser;
        private ViewGroup vg;
        private View view;
        private String t;

        Map attrs = new TreeMap();

        public Map getAttrs() {
            return attrs;
        }

        public boolean setTosettag;

        public ProduceView setSetTosettag(boolean setTosettag) {
            this.setTosettag = setTosettag;
            return this;
        }

        public ProduceView(XmlPullParser parser, ViewGroup vg, View view, String t) {
            this.parser = parser;
            this.vg = vg;
            this.view = view;
            this.t = t;
        }

        boolean is() {
            return myResult;
        }

        public View getView() {
            return view;
        }

        public String getT() {
            return t;
        }

        public ProduceView produceview() throws IllegalAccessException, NoSuchFieldException {
            String name = parser.getName();//view factory
            t = "";
            if (name.contains(".")) {

            } else if (name.endsWith("SurfaceView")) {
                name = "android.view." + name;
            } else {
                name = "android.widget." + name;
            }

            try {
                if (view == null) {

                    view = (View) Class.forName(name)
                            .getConstructor(Context.class)
                            .newInstance(aty);
                } else {
                    if (!name.equals(view.getClass().getName())) {
                        throw new RuntimeException("as params, 'name' is not same as 'view'.getClass().getName()");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return this;
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
        public ProduceView invoke() throws IllegalAccessException, NoSuchFieldException, NoSuchMethodException {
            try {
                if (vg == null) {
                    vg = (ViewGroup) view.getParent();
                }
                MapBuilder ps = MapBuilder.build().add("ViewGroup", new ViewGroup.MarginLayoutParams(-2, -2))
                        .add("FrameLayout", new FrameLayout.LayoutParams(-2, -2))
                        .add("RelativeLayout", new RelativeLayout.LayoutParams(-2, -2))
                        .add("LinearLayout", new LinearLayout.LayoutParams(-2, -2))
                        .add("GridLayout", new GridLayout.LayoutParams());
                if (view.getLayoutParams() == null) {
                    Class clzz = null;
                    try {
                        clzz = vg.getClass();
                    } catch (Exception e) {

                    }
                    ViewGroup.LayoutParams g;
                    while ((g = (ViewGroup.LayoutParams) ps.get().get(clzz.getSimpleName())) == null) {
                        clzz = clzz.getSuperclass();
                    }
                    if (g != null) {

                        view.setLayoutParams((ViewGroup.MarginLayoutParams) g);
                    }
                } else {
                    if (((ViewGroup.MarginLayoutParams) view.getLayoutParams()).leftMargin != 0) {

                    }
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            String tagvalue = "";
            t += "\n";
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                String n = parser.getAttributeName(i);
                n = n.replace("android:", "");
                String v = parser.getAttributeValue(i);
                t += "android:" + n + "=\"" + v + "\"\n";
                attrs.put(n, v);
                if (!settoview) {
                    continue;
                }
                if (n.equals("layout_width") || n.equals("layout_height")) {
                    if (vg != null) {
                        float px;
                        if (v.equals("fill_parent") || v.equals("match_parent")) {
                            px = -1;
                        } else if (v.equals("wrap_content")) {
                            px = -2;
                        } else {
                            px = dimenToPixel(v);
                        }
                        if (view == null) {
                            return this;
                        }
                        Object lps = ((ViewGroup.MarginLayoutParams) view.getLayoutParams());
                        lps.getClass().getField(n.replace("layout_", "")).set(lps, new Float(px + "").intValue());
                        view.requestLayout();
                    }
                } else if (n.contains("src")) {
                    if (!TextUtils.isEmpty(v) && v.contains("@drawable")) {
                        //默认内置
                        if (v.toString().endsWith("ic_launcher")) {
                            if (view instanceof ImageView) {
                                ((ImageView) view).setImageResource(R.drawable
                                        .ic_launcher);
                                //xml 串了
                            }
                        } else {
                            String objfilepath = "";
                            if (aty.getClass().getSimpleName().equals("RunActivity")) {
                                Field f = aty.getClass().getField("objfilepath");
                                f.setAccessible(true);
                                objfilepath = (String) f.get(aty);
                            } else if (aty.getClass().getSimpleName().equals("ViewActivity")) {
                                Field f = aty.getClass().getDeclaredField("objfilepath");
                                f.setAccessible(true);
                                objfilepath = (String) f.get(aty);
                                if (objfilepath == null) {
                                    Method m = aty.getClass().getDeclaredMethod("newpath");
                                    try {
                                        m.invoke(aty);
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    }
                                    f = aty.getClass().getDeclaredField("objfilepath");
                                    f.setAccessible(true);
                                    objfilepath = (String) f.get(aty);
                                }

                            }
                            if (objfilepath == null) {
                                //新建
                                ((ImageView) view).setImageResource(R.drawable.ic_launcher);
                            } else {

                                String path = v.replace("@drawable/", "");
                                path = path.replaceAll("\\.", "_");
//                                /storage/4BE6-151D/design/tmp25_xml/drawable/ss1_bdstatic_com_70cFuXSh_Q1YnxGkpoWK1HF6hhy_it_u=3476351472,2209247271_fm=26_gp=0_jpg
//                                /storage/4BE6-151D/design/tmp25_xml/drawable/ss1_bdstatic_com_70cFuXSh_Q1YnxGkpoWK1HF6hhy_it_u=3476351472,2209247271_fm=26_gp=0_jpg
                                String drawableP = objfilepath.replace(".xml", "_xml") + "/drawable/";
                                loadBitmapOrXml(drawableP + path);

//                                if (!new File(path).exists()) {
//                                    final String finalPath = path;
////                                    new Thread() {
////                                        @Override
////                                        public void run() {
////                                            super.run();
////                                            int i;
////                                            for (i = 0; i < 2; i++) {
////                                                try {
////                                                    Thread.sleep(500);
////                                                } catch (InterruptedException e) {
////                                                    e.printStackTrace();
////                                                }
////
////                                                if (loadBitmapOrXml(finalPath)) {
////                                                    return;
////                                                }
////                                            }
////                                            if (i == 2) {
////
////                                            }
////                                        }
////                                    }.start();
//
//                                    ToastUtil.live((Activity) view.getContext()).toast(finalPath);
//                                }
                            }
                        }
                    }
                } else if (n.contains("background")) {
                    if (view.getTag(R.id.uiflag) != null) {
                        if (view.getTag(R.id.uiflag).toString().equals("true")) {
                            view.setBackground(null);
                            view.setTag(R.id.uiflag, "rmbackground");
                        }
                    }
                    if (v.contains("@color")) {

                    } else if (v.contains("@drawable")) {
                        if (v.toString().endsWith("video")) {
//                            ((SurfaceView) view).setBackgroundResource(R.drawable.video);
                        } else {
                            String objfilepath = "";
                            if (aty.getClass().getSimpleName().equals("RunActivity")) {
                                objfilepath = (String) aty.getClass().getField("objfilepath").get(aty);
                            } else if (aty.getClass().getSimpleName().equals("ViewActivity")) {
                                Field f = aty.getClass().getDeclaredField("objfilepath");
                                f.setAccessible(true);
                                objfilepath = (String) f.get(aty);

                            }
                            String path = objfilepath + "/drawable" + "/" + v.replace("@drawable/", "").replaceAll("/", "_");
                            path = path.replaceAll("\\.", "_");
                            String p = v.substring(v.lastIndexOf("/") + 1);
                            p = objfilepath.replace(".xml", "_xml") + "/drawable" + "/" + p;
                            if (new File(p).exists()) {
                                if (!ImageFileUtil.isImage(p)) {
                                    String tc = ReadFileUtil.readsd(view.getContext(), p);
                                    if (TextUtils.isEmpty(tc)) {
                                        new File(p).delete();
                                    }
//                                    else
//                                        (view).setBackground(new StyleDrawable().setViewEffect(view, tc, false));
                                } else {
                                    x.image().loadDrawable(p, imageoptions, new Callback.CommonCallback<Drawable>() {
                                        @Override
                                        public void onSuccess(Drawable result) {
                                            (view).setBackgroundDrawable(result);
                                        }

                                        @Override
                                        public void onError(Throwable ex, boolean isOnCallback) {

                                        }

                                        @Override
                                        public void onCancelled(CancelledException cex) {

                                        }

                                        @Override
                                        public void onFinished() {

                                        }
                                    });
                                }
                            }
                        }
                    } else if (v.contains("#")) {
                        int color = Color.parseColor(v);
                        view.setBackgroundColor(color);
                    } else if (TextUtils.isEmpty(v)) {
                        view.setBackground(null);
                    } else {
                        ToastUtil.live(aty).toast(v);

                    }
                } else if (n.contains("padding")) {

                    if (n.contains("@dimension")) {

                    } else {
                        int p = (int) dimenToPixel(v);
                        if (n.toLowerCase().contains("left")) {
                            setPadding(view, p, -1, -1, -1);
                        } else if (n.toLowerCase().contains("top")) {
                            setPadding(view, -1, p, -1, -1);
                        } else if (n.toLowerCase().contains("right")) {
                            setPadding(view, -1, -1, p, -1);
                        } else {
                            setPadding(view, -1, -1, -1, p);
                        }

                    }
                } else if (n.contains("layout_weight")) {
                    if (view instanceof LinearLayout) {
                        if (view.getLayoutParams() != null) {
                            ((LinearLayout.LayoutParams) ((LinearLayout) view).getLayoutParams()).weight = Integer.parseInt(n);

                        }
                    }
                } else if (n.contains("layout_margin")) {
                    if (vg != null) {
                        if (v.contains("@dimension")) {

                        } else {
                            int p = (int) dimenToPixel(v);
                            if (n.toLowerCase().contains("left")) {
                                ((ViewGroup.MarginLayoutParams) view.getLayoutParams()).leftMargin = p;
                            } else if (n.toLowerCase().contains("top")) {
                                ((ViewGroup.MarginLayoutParams) view.getLayoutParams()).topMargin = p;
                            } else if (n.toLowerCase().contains("right")) {
                                ((ViewGroup.MarginLayoutParams) view.getLayoutParams()).rightMargin = p;
                            } else {
                                ((ViewGroup.MarginLayoutParams) view.getLayoutParams()).bottomMargin = p;
                            }

                        }
                    }
                } else if (n.contains("alignParent") && vg != null && vg instanceof RelativeLayout) {
                    if (view.getLayoutParams() == null) {
                        view.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
                    }
                    if (view.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
                        MapBuilder mb = MapBuilder.build().add("left", RelativeLayout.ALIGN_PARENT_LEFT)
                                .add("top", RelativeLayout.ALIGN_PARENT_TOP)
                                .add("right", RelativeLayout.ALIGN_PARENT_RIGHT)
                                .add("bottom", RelativeLayout.ALIGN_PARENT_BOTTOM)
                                .add("start", RelativeLayout.ALIGN_PARENT_START)
                                .add("end", RelativeLayout.ALIGN_PARENT_END);
                        Integer align = (Integer) mb.get().get(n.toLowerCase().replace("layout_alignparent", ""));
                        if (align != null) {
                            if (v.equals("true")) {
                                ((RelativeLayout.LayoutParams) view.getLayoutParams()).addRule(align);
                            } else {
                                ((RelativeLayout.LayoutParams) view.getLayoutParams()).removeRule(align);
                            }
                        }
                    }
                } else if (n.contains("layout_center")) {
                    if (view.getLayoutParams() == null) {
                        view.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
                    }
                    if (view.getLayoutParams() instanceof RelativeLayout.LayoutParams) {
                        MapBuilder mb = MapBuilder.build().add("vertical", RelativeLayout.CENTER_VERTICAL)
                                .add("horizontal", RelativeLayout.CENTER_HORIZONTAL)
                                .add("inparent", RelativeLayout.CENTER_IN_PARENT);
                        Integer align = (Integer) mb.get().get(n.toLowerCase().replace("layout_center", ""));
                        if (align != null) {
                            if (v.equals("true")) {
                                ((RelativeLayout.LayoutParams) view.getLayoutParams()).addRule(align);
                            } else {
                                ((RelativeLayout.LayoutParams) view.getLayoutParams()).removeRule(align);
                            }
                        }
                    }
                } else if (n.equals("gravity")) {
                    MapBuilder mb = MapBuilder.build();
                    mb.add("center_horizontal", Gravity.CENTER_HORIZONTAL)
                            .add("clip_vertical", Gravity.CLIP_VERTICAL)
                            .add("end", Gravity.END)
                            .add("right", Gravity.RIGHT)
                            .add("fill_vertical", Gravity.FILL_VERTICAL)
                            .add("bottom", Gravity.BOTTOM)
                            .add("fill", Gravity.FILL)
                            .add("center_vertical", Gravity.CENTER_VERTICAL)
                            .add("left", Gravity.LEFT)
                            .add("top", Gravity.TOP)
                            .add("clip_horizontal", Gravity.CLIP_HORIZONTAL)
                            .add("fill_horizontal", Gravity.FILL_HORIZONTAL)
                            .add("center", Gravity.CENTER);
                    String[] attrs = v.replaceAll(" ", "").split("\\|");
                    Integer values = null;
                    for (String a : attrs) {
                        Integer gravity = (Integer) mb.get().get(a.toLowerCase());
                        if (values == null) {
                            values = gravity;
                        } else {
                            if (gravity != null) {
                                values |= gravity.intValue();
                            }
                        }
                    }
                    if (values != null && view instanceof TextView) {
                        ((TextView) view).setGravity(values);
                    }
                } else if (n.contains("layout_gravity")) {
                    MapBuilder mb = MapBuilder.build();
                    mb.add("start", Gravity.START)
                            .add("center_horizontal", Gravity.CENTER_HORIZONTAL)
                            .add("clip_vertical", Gravity.CLIP_VERTICAL)
                            .add("end", Gravity.END)
                            .add("right", Gravity.RIGHT)
                            .add("fill_vertical", Gravity.FILL_VERTICAL)
                            .add("bottom", Gravity.BOTTOM)
                            .add("fill", Gravity.FILL)
                            .add("center_vertical", Gravity.CENTER_VERTICAL)
                            .add("left", Gravity.LEFT)
                            .add("top", Gravity.TOP)
                            .add("clip_horizontal", Gravity.CLIP_HORIZONTAL)
                            .add("fill_horizontal", Gravity.FILL_HORIZONTAL)
                            .add("center", Gravity.CENTER);
                    String[] attrs = v.split("\\|");
                    Integer values = null;
                    for (String a : attrs) {
                        Integer gravity = (Integer) mb.get().get(a.toLowerCase());

                        if (values == null) {
                            values = gravity;
                        } else {
                            if (gravity != null) {
                                values |= gravity.intValue();
                            }
                        }
                    }
                    if (values != null && view instanceof LinearLayout) {
                        LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) view.getLayoutParams();
                        ll.gravity = values;
                    }

                } else if (n.equals("text")) {

                    if (view instanceof TextView) {

                        ((TextView) view).setText(v);
                    }

                } else if (n.equals("hint")) {

                    if (view instanceof TextView) {

                        ((TextView) view).setHint(v);
                    }

                } else if (n.equals("textColorHint")) {

                    if (view instanceof TextView) {
                        if (v.contains("@color")) {

                        } else
                            ((TextView) view).setHintTextColor(Color.parseColor(v));
                    }
                } else if (n.toLowerCase().equals("textcolor")) {

                    if (view instanceof TextView) {
                        if (v.contains("@color")) {

                        } else if (v.contains("@android:color")) {

                        } else {
                            ((TextView) view).setTextColor(Color.parseColor(v));
                        }

                    }


                } else if (n.toLowerCase().equals("textsize")) {
                    if (v.contains("@dimension")) {

                    }
                    if (view instanceof TextView) {
                        if (v.contains("dip")) {
                            ((TextView) view).setTextSize(TypedValue.COMPLEX_UNIT_DIP, Float.parseFloat(v.substring(0, v.length() - 3)));
                        } else {
                            ((TextView) view).setTextSize(dimenToPixel(v));
                        }
                    }

                } else if (n.toLowerCase().equals("lines")) {
                    if (v.contains("@integer")) {

                    } else {
                        if (view instanceof TextView) {
                            ((TextView) view).setLines(Integer.parseInt(v));
                        }
                    }

                } else if (n.toLowerCase().equals("maxLines")) {
                    if (v.contains("@integer")) {

                    } else {
                        if (view instanceof TextView) {
                            ((TextView) view).setMaxLines(Integer.parseInt(v));
                        }
                    }

                } else if (n.toLowerCase().equals("ellipsize")) {
                    if (v.contains("@integer")) {

                    } else {
                        if (view instanceof TextView) {
                            MapBuilder mb = MapBuilder.build().add("end", TextUtils.TruncateAt.END)
                                    .add("marquee", TextUtils.TruncateAt.MARQUEE)
                                    .add("middle", TextUtils.TruncateAt.MIDDLE)
                                    .add("start", TextUtils.TruncateAt.START);
                            ((TextView) view).setEllipsize((TextUtils.TruncateAt) mb.get().get(v));
                        }
                    }

                } else if (n.toLowerCase().equals("digits")) {
                    if (view instanceof EditText) {
                        ((EditText) view).setKeyListener(DigitsKeyListener.getInstance(v));
                    }
                } else if (n.toLowerCase().equals("orientation")) {

                    if (view instanceof LinearLayout) {
                        MapBuilder mb = MapBuilder.build().add("vertical", LinearLayout.VERTICAL)
                                .add("horizontal", LinearLayout.HORIZONTAL);
                        ((LinearLayout) view).setOrientation((Integer) mb.get().get(v));
                    }
                } else if (n.toLowerCase().equals("id")) {
                    view.setTag(R.id.tag_id, v.replace("@+id/", "@id/"));

                } else if (n.toLowerCase().contains("layout_to") || n.toLowerCase().equals("layout_above") || n.toLowerCase().equals("layout_below")) {

                } else if (n.toLowerCase().equals("tag")) {
                    tagvalue = v;
                } else if (n.equals("numColumns")) {
                    ((GridView) view).setNumColumns(Integer.parseInt(v));
                } else if (n.equals("scaleType")) {

//ImageView.ScaleType iv = null;
//                    if(v.contains("\\|")){
//String[] scale = v.split("|");
//for(String s:scale){
//    if(iv==null){
//    iv=ImageView.ScaleType.valueOf(s.toString());
//
//    }else{
//        iv = ImageView.ScaleType.valueOf(s) | iv;
//    }
//
//}
                    if (v.toUpperCase().equals("NONE")) {
                        ((ImageView) view).setScaleType(ImageView.ScaleType.FIT_CENTER);

                    } else if (v.equals("centerCrop")) {
                        ((ImageView) view).setScaleType(ImageView.ScaleType.CENTER_CROP);

                    } else if (v.toLowerCase().equals("centerinside")) {
                        ((ImageView) view).setScaleType(ImageView.ScaleType.CENTER_INSIDE);

                    } else if (v.toLowerCase().equals("center")) {
                        ((ImageView) view).setScaleType(ImageView.ScaleType.CENTER);

                    } else if (v.toLowerCase().equals("fitcenter")) {
                        ((ImageView) view).setScaleType(ImageView.ScaleType.FIT_CENTER);

                    } else
                        ((ImageView) view).setScaleType(ImageView.ScaleType.valueOf(v.toString()));
                } else if (n.equals("textStyle")) {
                    MapBuilder mapBuilder = MapBuilder.build().add("bold", Typeface.BOLD)
                            .add("italic", Typeface.ITALIC)
                            .add("italic_bold", Typeface.BOLD_ITALIC)
                            .add("bold_italic", Typeface.BOLD_ITALIC)
                            .add("normal", Typeface.NORMAL);
                    ((TextView) view).setTypeface(Typeface.defaultFromStyle((Integer) mapBuilder.get(v.toString())));
                }
            }


            if (!TextUtils.isEmpty(tagvalue)) {
                ViewInflater.tagrate(view, tagvalue, view.getContext());
                view.setTag(tagvalue);
                if (view.getContext().getClass().getSimpleName().equals("RunActivity")) {
                    ViewInflater.clickrate(view, tagvalue, view.getContext());
                }
            }
            if (setTosettag) {

                t = "<" + parser.getName() + "  xmlns:android=\"http://schemas.android.com/apk/res/android\"" + t + "/>";
                if (t.contains("xml:")) {
                    int j = 0;
                    j++;
                }
                t = t.replaceAll("\n\n", "\n");
                view.setTag(R.id.xml, t);
            }

            myResult = false;
            return this;
        }

        private boolean loadBitmapOrXml(String path) {
            if (new File(path).exists()) {

                if (!ImageFileUtil.isImage(path)
                    //!TextUtils.isEmpty(tc) && tc.contains("xmlns:android")
                ) {
                    final String tc = ReadFileUtil.readsd(view.getContext(), path);
                    if (TextUtils.isEmpty(tc)) {
                        new File(path).delete();
                        return false;
                    }
//                    new Handler(Looper.getMainLooper(), new Handler.Callback() {
//                        @Override
//                        public boolean handleMessage(Message message) {
//                            ((ImageView) view).setImageDrawable(new StyleDrawable().setViewEffect(view, tc, false));
//                            return false;
//                        }
//                    }).sendEmptyMessage(0);
                } else {
                    if (imageoptions == null) {
                        imageoptions = new ImageOptions.Builder()
//                                .setConfig(Bitmap.Config.RGB_565)//设置图片质量,这个是默认的
//                                .setFadeIn(true)//淡入效果
                                //需成对使用
//                                .setLoadingDrawable(new ColorDrawable(Color.parseColor("#88000000")))//图片正在加载时显示的默认图片
//                                .setUseMemCache(true)//设置缓存，默认为true
                                .build();
                    }
                    x.image().bind(((ImageView) view), path, new Callback.CommonCallback<Drawable>() {
                        @Override
                        public void onSuccess(Drawable result) {
                            final Bitmap bitmap = ((BitmapDrawable) result).getBitmap();
                            String xml = (String) ((ImageView) view).getTag(R.id.xml);
                            if (xml.contains("wrap_content") || xml.contains("_parent")) {
                                BroadcastBuilder.get(BroadcastBuilder.class, aty).sendAction("addline", "", aty, MapBuilder.build().add("layout_width", DipUtil.px2dip(bitmap.getWidth()) + "dip").add("layout_height", DipUtil.px2dip(bitmap.getHeight()) + "dip"), BroadcastBuilder.Starttype.broadcast);
                            }

                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {

                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
//                    x.image().loadDrawable(path, imageoptions, new Callback.CommonCallback<Drawable>() {
//                        @Override
//                        public void onSuccess(final Drawable result) {
//                            new Handler(Looper.getMainLooper(), new Handler.Callback() {
//                                @Override
//                                public boolean handleMessage(Message message) {
//                                    ((ImageView) view).setImageDrawable(result);
//                                    return false;
//                                }
//                            }).sendEmptyMessage(0);
//                            }
//
//                        @Override
//                        public void onError(Throwable ex, boolean isOnCallback) {
//
//                        }
//
//                        @Override
//                        public void onCancelled(CancelledException cex) {
//
//                        }
//
//                        @Override
//                        public void onFinished() {
//
//                        }
//                    });
//                    final Bitmap bitmap = BitmapFactory.decodeFile(path);
//
////                                        view.getLayoutParams().width = bitmap.getWidth();
////                                        view.getLayoutParams().height = bitmap.getHeight();s
////                                        view.invalidate();
//                    new Handler(Looper.getMainLooper(), new Handler.Callback() {
//                        @Override
//                        public boolean handleMessage(Message message) {
//                            ((ImageView) view).setImageBitmap(bitmap);
//                            return false;
//                        }
//                    }).sendEmptyMessage(0);

                }
            }
            return new File(path).exists();
        }
    }
}
